#!/usr/bin/perl

package Ldif::Creator;

use warnings;
use strict;
use Data::Dumper;
use Class::Std;
use JSON;
use Net::LDAP::LDIF;
use Net::LDAP::Entry;

{

    sub BUILD {
        my ( $self, $obj_ID, $arg_ref ) = @_;

    }

    sub write_entry_to_file {
        my ( $self, $value, $ldif ) = @_;

        my $entry = Net::LDAP::Entry->new();
        $entry->dn( $value->{dn} );
        delete $value->{dn};
        if ( $value->{objectClass} ) {
            $value->{objectClass} = "top " . $value->{objectClass} unless $value->{objectClass} =~ m/top/;
        }
        else { $value->{objectClass} = "top"; }

        $entry->add( $_ => $value->{$_} ) foreach ( keys %$value );

        $ldif->write_entry($entry);
    }

    sub create_ldif {
        my ( $self, $json_text, $file_name ) = @_;

        return 0 unless ( $file_name || $json_text );
        my $values = from_json( $json_text, { utf8 => 1 } );
        my $ldif = Net::LDAP::LDIF->new( $file_name, "w", onerror => 'undef', sort => 1 );
        return 0 unless $ldif;

        write_entry_to_file( $self, $_, $ldif ) foreach (@$values);
        $ldif->done();
        return 1;
    }

    sub read_from_ldif {
        my ( $self, $file_name ) = @_;

        my $ldif = Net::LDAP::LDIF->new( $file_name, "r", onerror => 'undef' );
        return 0 unless $ldif;

        my @entries;
        while ( not $ldif->eof() ) {
            my $entry = $ldif->read_entry();
            if ( $ldif->error() ) {
                print "Error msg: ",    $ldif->error(),       "\n";
                print "Error lines:\n", $ldif->error_lines(), "\n";
            }
            else {
                my $value;
                $value->{dn} = $entry->dn;
                $value->{$_} = $entry->get_value($_) foreach ( $entry->attributes );
                $value->{objectClass} =~ s/top//;

                push @entries, $value;
            }
        }
        $ldif->done();

        print Dumper \@entries;
        return to_json( \@entries );
    }

}

1;
